package com.dage.salesflow.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.stp.StpUtil;
import com.dage.salesflow.constant.SysConstant;
import com.dage.salesflow.kit.Ret;
import com.dage.salesflow.kit.WebKit;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;

public class AuthInterceptor implements Interceptor {
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		try {
			StpUtil.checkLogin();
			inv.invoke();
		} catch (NotLoginException e) {
			// 判断场景值，定制化异常信息
			LogKit.warn(e.getMessage());
			if (WebKit.isAjaxRequest(controller.getRequest())) {
				// 判断场景值，定制化异常信息
				Ret ret;
				if (e.getType().equals(NotLoginException.BE_REPLACED)) {
					ret = Ret.err(SysConstant.BE_REPLACED);
				} else if (e.getType().equals(NotLoginException.KICK_OUT)) {
					ret = Ret.err(SysConstant.KICK_OUT);
				} else {
					ret = Ret.err(SysConstant.NO_LOGIN);
				}
				controller.renderJson(ret);
			} else {
				controller.redirect("/login.html");
			}
		} catch (NotPermissionException e) {
			// 权限不足
			LogKit.warn(e.getMessage());
			if (WebKit.isAjaxRequest(controller.getRequest())) {
				controller.renderJson(Ret.err("对不起，权限不足！" + e.getMessage()));
			} else {
				controller.redirect("/err/401.html");
			}
		} catch (NotRoleException e) {
			// 角色鉴权失败
			LogKit.warn(e.getMessage());
			if (WebKit.isAjaxRequest(controller.getRequest())) {
				controller.renderJson(Ret.err("对不起，用户角色权限不足！" + e.getMessage()));
			} else {
				controller.redirect("/err/401.html");
			}
		}
	}
}
